package com.javalearn.gulimail.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.javalearn.common.To.mq.OrderTo;
import com.javalearn.common.To.mq.StockDetailTo;
import com.javalearn.common.To.mq.StockLockedTo;
import com.javalearn.common.constant.ProductConstant;
import com.javalearn.common.utils.R;
import com.javalearn.gulimail.ware.entity.WareOrderTaskDetailEntity;
import com.javalearn.gulimail.ware.entity.WareOrderTaskEntity;
import com.javalearn.gulimail.ware.exception.NoStockException;
import com.javalearn.gulimail.ware.feign.OrderFeignService;
import com.javalearn.gulimail.ware.feign.ProductFeignService;
import com.javalearn.gulimail.ware.service.WareOrderTaskDetailService;
import com.javalearn.gulimail.ware.service.WareOrderTaskService;
import com.javalearn.gulimail.ware.vo.*;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javalearn.common.utils.PageUtils;
import com.javalearn.common.utils.Query;

import com.javalearn.gulimail.ware.dao.WareSkuDao;
import com.javalearn.gulimail.ware.entity.WareSkuEntity;
import com.javalearn.gulimail.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")

public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    OrderFeignService orderFeignService;



    private void unLockStovk(Long skuId,Long wareId,Integer num,Long taskDeatilId){
        wareSkuDao.unlockStock(skuId,wareId,num);
        //更新库存工作单的状态，修改为2，已解锁
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDeatilId);
        entity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(entity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {    QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();

        //查询条件
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //先判断如果还没有这个库存记录，那就是新增操作
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (entities==null || entities.size()==0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //远程查询sku的名字,如果失败整个事务不需要回滚
            //1.自己catch异常
            //TODO 还有什么方法让异常出现后不会滚呢？
            try {
                R r = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) r.get("skuInfo");
                if (r.getCode() == 0){
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){}

            wareSkuDao.insert(wareSkuEntity);
        }else {
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId-> {
            SkuHasStockVo vo = new SkuHasStockVo();

            //查询当前sku的总库存量
            //SELECT sum(stock-stock_locked) FROM `wms_ware_sku` where sku_id = 22
            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count==null?false:count>0);
            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 为某个订单锁定库存
     * @param
     * @return
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单详情
         * 便于后续的回滚追溯
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);


        //按照下单的收货地址，找到一个就近仓库，锁定库存（了解）

        //1.找到每个商品在那个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareId = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareId);
            return stock;
        }).collect(Collectors.toList());

        Boolean allLock = true;
        //2.锁定库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds==null || wareIds.size()==0){
                //没有任何仓库有库存,订单结束
                throw new NoStockException(skuId);
            }else {
                //1.如果每一个商品都锁定成功，将当前商品锁定了几件的工作单记录发给mq
                //2.锁定失败，前面保存的工作单信息就回滚了，发送出去的消息即使要解锁记录，由于数据库回滚了，查不到id，所以也就不用解锁
                for (Long wareId:wareIds){
                    //成功就返回1，不成功就是0
                    Long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                    if (count==1){
                        skuStocked = true;
                        //TODO 告诉mq库存锁定成功
                        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                        wareOrderTaskDetailService.save(entity);
                        StockLockedTo lockedTo = new StockLockedTo();
                        lockedTo.setId(taskEntity.getId());
                        StockDetailTo stockDetailTo = new StockDetailTo();
                        BeanUtils.copyProperties(entity,stockDetailTo);
                        //只发id不行，防止回滚以后找不到数据
                        lockedTo.setDetail(stockDetailTo);
                        rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                        break;
                    }else {
                        //当前仓库锁失败了，重试下一个仓库
                    }
                }
                if (!skuStocked){
                    //当前商品所有仓库都没锁住
                    throw new NoStockException(skuId);
                }
            }
        }

        //3.能走到这肯定全部都是锁定成功的
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        Long id = to.getId();//库存工作单的id
        StockDetailTo detail = to.getDetail();
        Long skuId = detail.getSkuId();
        Long detailId = detail.getId();
        //解锁
        //1.查询数据库关于这个订单的锁定库存消息
        //有：证明库存是锁定成功的，到底要不要解锁，看订单情况
        //1.没有这个订单，必须解锁
        //2.有这个订单，看订单状态，如果是已取消，只要没取消，就不能解锁库存
        //没有：库存锁定失败了，库存回滚了，这种情况无需解锁
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if (byId!=null){
            //解锁
            Long id1 = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            //根据订单号，查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode()==0){
                //订单数据返回成功
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                if (data==null || data.getStatus() == 4){
                    //订单不存在或订单是取消状态，才能解锁库存
                    if (byId.getLockStatus()==1){
                        //当前工作单状态详情是1，已锁定但未解锁才可以解锁
                        unLockStovk(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    }
                }
            }else {
                //消息拒绝以后重新放回队列，让别人继续消费解锁
                throw new RuntimeException("远程服务失败");
            }
        }else {
            //无需解锁
        }
    }

    /**
     * 防止订单服务卡顿，导致订单消息状态一直改不了，库存消息先到，查询订单新建状态，什么都不做就走了
     * 导致库存解锁失败
     * @param orderTo
     */
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新库存的状态，防止重复解锁库存
        //找到库存工作单
        WareOrderTaskEntity task = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        //按照库存工作单，找到所有没有解锁的库存进行解锁
        List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1));

        for (WareOrderTaskDetailEntity entity : entities) {
            unLockStovk(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }
    }

    //内部类来封装库存信息
    @Data
    class SkuWareHasStock{
        private Long skuId;//商品的id
        private Integer num;//锁多少个
        private List<Long> wareId;//商品在哪个仓库中有库存
    }

}